<template>
  <div class="container">
    <salaryTopTitle @gobackTriser="goBack"></salaryTopTitle>

    <!--制作工资表-->
    <div class="mainCon">
      <createSalaryStep :activeIndex="activeIndex"></createSalaryStep>
      <div class="createPayWin">
        <p>创建工资表</p>
        <el-row class="toolbar" style="padding-bottom: 0">
          <el-form
            :model="formData"
            label-width="85px"
            ref="formData"
            :rules="formRules"
          >
            <el-row class="row-padding-bottom">
              <el-col>
                <el-form-item label="创建方式">
                  <el-input
                    v-model="createWay"
                    disabled="disabled"
                    class="createWay"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="row-padding-bottom">
              <el-col>
                <el-form-item label="发薪项目">
                  <el-input
                    v-model="projectName"
                    disabled="disabled"
                    class="companyName"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- <el-row class="row-padding-bottom">
            <el-col>
              <el-form-item label="发薪月份" prop="month">
                 <el-date-picker
                    v-model="formData.month"
                    type="month"
                    value-format="yyyy-MM"
                    placeholder="选择月">
                    </el-date-picker>
              </el-form-item>
            </el-col>
            </el-row>-->
            <el-row class="row-padding-bottom">
              <el-col>
                <el-form-item label="选择文件" prop="excel">
                  <!-- <el-input v-model="input" type="input"></el-input> -->
                  <span class="uploadBox el-input__inner">
                    <!-- <uploadInput ref="uploadInput" :placeholder="placeholder"></uploadInput> -->
                    <form id="salaryExcelForm">
                      <input
                        type="file"
                        id="salaryExcel"
                        name="salaryExcel"
                        placeholder="placeholder"
                        @change="upLoadExcel"
                      />
                      <!-- <input type="text" v-model="projectId" name="projectId" style="display:none" /> -->
                      <!-- <input type="text" v-model="month" name="month" style="display:none"/> -->
                    </form>
                  </span>
                  导入的工资表应与模板格式一致，
                  <el-link type="primary" @click="downLoad('csSalaryExcel')"
                    >点击下载工资表模板</el-link
                  >
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="row-padding-bottom">
              <el-button
                class="commonBut saveBtn"
                @click="toImportSalary"
                :loading="isAdd"
                >导入</el-button
              >
              <el-button class="commonBut" @click="goBack"
                >返回上一页</el-button
              >
              <!-- <div class="goBack" @click="goBack">
               <i class="icon iconfont iconfanhui"></i> 返回上一页
              </div>-->
            </el-row>
          </el-form>
        </el-row>
      </div>
    </div>

    <el-dialog
      title="提示"
      :visible.sync="formVisible"
      :close-on-click-modal="false"
      @close="closeDialog"
      custom-class="dialog-minwidth"
      :modal-append-to-body="false"
      center
      width="500px"
      :append-to-body="true"
    >
      <div class="errorBox">
        {{ errorNotice }}
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click.native="closeDialog"
          class="save"
          v-show="isShowAdd"
          >确认</el-button
        >
        <!-- <el-button @click.native="closeDialog" class="cancel">取消</el-button> -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import common from '../../kits/common'
import createSalaryStep from '@/components/publicCom/createSalaryStepJz'
import salaryTopTitle from '@/components/publicCom/salaryTopTitle'

export default {
  name: 'importSalary',
  components: {
    createSalaryStep,
    salaryTopTitle,
  },
  data() {
    var checkInput = (rule, value, callback) => {
      var that = this
      setTimeout(function () {
        var val = $('#salaryExcel').val()
        if (!val) {
          return callback(new Error('请选择需要导入的工资表'))
        } else {
          callback()
        }
      }, 1000)
    }
    return {
      createWay: '导入工资表',
      activeIndex: 0,
      comapnyName: '公司名称',
      placeholder: '请选择Excel文件',
      formData: {},
      formRules: {
        excel: [
          {
            required: true,
            // pattern: /^[\s\S]*.*[^\s][\s\S]*$/,
            // message: "请选择",
            validator: checkInput,
            trigger: 'blur',
          },
        ],
        // month: [
        //   {
        //     required: true,
        //     pattern: /^[\s\S]*.*[^\s][\s\S]*$/,
        //     message: "请选择生成工资表的发薪月份",
        //     trigger: "change"
        //   }
        // ]
      },
      //   year:"",
      //   month:"",
      formVisible: false,
      errorNotice: '',
      isAdd: false,
      projectName: '',
      projectId: '',
      isShowAdd: '',
      noRegisEmployee: [],
    }
  },
  created() {
    // this.nickName = this.$store.state.nickName;
    // this.projectId = '111'
    this.projectId = this.$route.query.projectId
    this.projectName = this.$route.query.projectName
    this.isShowAdd =
      this.$store.state.buttonLimitsArr.indexOf('csSalaryList:add') > -1
  },
  methods: {
    toImportSalary() {
      this.isAdd = true
      this.$refs.formData.validate((valid) => {
        if (valid) {
          //   this.year = this.formData.month.split("-")[0]; //年
          //   this.month = this.formData.month.split("-")[1]; //月
          var that = this
          var Filedata = $('#salaryExcel').val()

          if (!/\.(xls|xlsx)$/.test(Filedata)) {
            this.$message({
              message: 'excel类型必须是.xls,xlsx中的一种',
              type: 'warning',
            })
            this.isAdd = false
            $('#salaryExcel').val('')
            return
          }

          setTimeout(function () {
            //that.isAdd = true;
            that.uploadFileByAjaxSubmit(
              //   "api-su/cs/salary/expand/importExcel",
              'api-su/cs/salary/expand/excelnew',
              that.success,
              that.error
            )
          }, 500)
        } else {
          this.isAdd = false
          // this.$refs.detail.validateField('pictureIds')
        }
      })
    },
    upLoadExcel() {
      this.$refs.formData.validateField('excel')
    },
    success(data) {
      this.isAdd = false
      if (!data.hasError) {
        this.$message({
          message: data.msg,
          type: 'success',
        })
        //导入成功 跳转到工资表管理页面

        this.$router.push({
          path: '/home/salaryDf/companySalaryBatchList',
          name: 'companySalaryBatchList',
          query: {
            projectName: this.projectName,
            projectId: this.projectId,
          },
        })
        this.$store.commit('CHANGE_SLIDER_NAME', {
          oldUrl: '/home/salaryDf/companySalaryBatchList',
          newUrl: this.$router.currentRoute.fullPath,
        })
      } else {
        //导入未录入人员功能砍掉
        this.$alert(data.errorMsg, {
          confirmButtonText: '确定',
          center: true,
          callback: (action) => {
            return false
          },
        })
        // this.errorNotice = data.errorMsg;
        // this.formVisible = true;
        // this.noRegisEmployee = data.result
      }
    },
    closeDialog() {
      this.formVisible = false
    },
    //根据状态码判断是否是401
    error(XMLHttpRequest, textStatus, errorThrown) {
      if (XMLHttpRequest.status === '401' || XMLHttpRequest.status === '403') {
        localStorage.setItem('access_token', '')
        localStorage.setItem('refresh_token', '')
        localStorage.setItem('userName', '')
        // 只有在当前路由不是登录页面才跳转
        if (router.currentRoute.path !== '/login/loginFirst') {
          router.replace({
            path: '/login/loginFirst',
          })
        }
        //清除tab栏数据
        this.$store.state.sliderBar = []
        localStorage.removeItem('sliderBar')
      } else {
        this.isAdd = false
        this.$message({
          message: '数据请求失败',
          type: 'warning',
        })
      }
    },
    uploadFileByAjaxSubmit(url, successCallBack, errorCallBack) {
      let that = this
      var token = localStorage.getItem('access_token')
      var options = {
        url: common.uploadUrl + url,
        type: 'POST',
        data: { projectId: that.projectId },
        dataType: 'json',
        headers: { Authorization: 'Bearer ' + token },
        contentType: false,
        processData: false,
        success: function (data) {
          successCallBack(data)
          $('#salaryExcel').val('')
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          errorCallBack(XMLHttpRequest, textStatus, errorThrown)
        },
        //		resetForm: true
      }
      //	$("#uploadFileForm").ajaxSubmit(options);
      //$(".uploadFileForm").ajaxSubmit(options);
      //$("from").ajaxSubmit(options);
      //三种方式均可
      $('#salaryExcelForm').ajaxSubmit(options)
      // $(dom).ajaxSubmit(options);
      return false
    },
    downLoad(type) {
      this.axios({
        method: 'post',
        url: 'api-su/salary/expand/findurl',
        data: {
          name: type,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            window.open(response.data.result.url)
          } else {
            this.$message({
              type: 'error',
              message: response.data.msg,
            })
          }
        })
        .catch((error) => {})
    },
    goBack() {
      // this.$router.push("/home/constructSalary/createConstructSalaryWay");
      this.$router.push({
        path: '/home/constructSalary/createConstructSalaryWay',
        name: 'createConstructSalaryWay',
        query: {
          projectName: this.projectName,
          projectId: this.projectId,
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/salaryDf/companySalaryBatchList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    sureDialog() {
      this.axios({
        method: 'post',
        url: 'api-su/cs/salary/expand/savenew',
        data: {
          jsonObject: JSON.stringify(this.noRegisEmployee),
          projectId: this.projectId,
        },
      }).then((response) => {
        if (!response.data.hasError) {
          let data = response.data
          this.$router.push({
            path: '/home/constructSalary/editConstructSalary',
            name: 'editConstructSalary',
            query: {
              salaryId: data.result.list[0].salaryId,
              month: data.result.list[0].month,
              year: data.result.list[0].year,
              projectId: this.projectId,
              projectName: this.projectName,
              type: 'import',
            },
          })
          this.$store.commit('CHANGE_SLIDER_NAME', {
            oldUrl: '/home/salaryDf/companySalaryBatchList',
            newUrl: this.$router.currentRoute.fullPath,
          })
        } else {
          this.$message({
            type: 'error',
            message: response.data.msg,
          })
        }
      })
    },
  },
}
</script>

<style scoped lang="less">
.mainCon {
  top: 197px;
}

.el-form-item {
  margin-bottom: 28px;
}

.createPayWin {
  margin-top: 60px;
  text-align: center;
  margin-bottom: 0;
  padding-bottom: 70px;
  p {
    font-size: 28px;
    color: #333;
    font-family: '宋体';
    margin-bottom: 60px;
  }
  .el-form {
    display: inline-block;
    width: 460px;
    /deep/ .el-form-item__content {
      width: 340px;
    }
    /deep/ .el-input {
      width: 340px;
    }

    .commonBut {
      margin-top: 8px;
    }
    .goBack {
      margin-top: 22px;
      font-size: 14px;
      color: #999;
      cursor: pointer;
      i {
        vertical-align: middle;
      }
    }
    .createWay /deep/ input {
      font-size: 14px;
      color: #666;
      background: #bfc5cc;
      border: 1px solid #bfc5cc;
    }
    .companyName /deep/ input {
      border: none;
      color: #666;
    }
  }
  /deep/ .toolbar {
    padding: 0;
  }
  .uploadBox {
    line-height: 36px;
    width: 100%;
    text-align: left;
    /deep/ form {
      display: inline-block;
    }
  }
}

.errorNoticeBox {
  text-align: center;
  margin-bottom: 24px;
  i {
    color: red;
    font-size: 50px;
  }
}
.errorBox {
  line-height: 24px;
}

.el-link {
  height: 20px;
  line-height: 20px;
}
</style>
